package com.fc.controller;

import com.fc.Base.BaseController;
import com.fc.model.RechargeLog;
import com.fc.model.User;
import com.fc.service.RechargeLogService;
import com.fc.service.UserService;
import com.fc.util.HttpKit;
import com.fc.util.IdWorker;
import com.fc.util.IpKit;
import com.fc.util.PageData;
import com.fc.util.PaymentApi;
import com.fc.util.PaymentKit;
import com.fc.util.Tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import static com.fc.util.ConstantParams.appid;
import static com.fc.util.ConstantParams.mch_id;
import static com.fc.util.ConstantParams.mch_key;
import static com.fc.util.ConstantParams.recharge_notify_url;

/**
 * 账户中心
 * Created by yukai on 2017/2/8.
 */
@Controller
@RequestMapping("/")
public class AccountController extends BaseController{

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RechargeLogService rechargeLogService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 微信充值扫码回调地址
     * @return
     */
    @RequestMapping(value = "/scanNotify.do")
    @ResponseBody
    public Object sanvnei(){
        logger.error("微信商家充值扫码支付回调");
        // 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
        String xmlMsg = HttpKit.readData(getRequest());
        logger.error("支付通知="+xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);

        String result_code  = params.get("result_code");
        // 总金额
        String totalFee     = params.get("total_fee");
        // 商户订单号
        String orderNo      = params.get("out_trade_no");
        // 微信支付订单号
        String transId      = params.get("transaction_id");
        // 支付完成时间，格式为yyyyMMddHHmmss
        String timeEnd      = params.get("time_end");
        String key = transId+timeEnd;
        Jedis jedis = jedisPool.getResource();
        if(!jedis.sismember(key, key)) {
            jedis.sadd(key, key);
            System.out.println("-----come cache------");
            // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
            // 避免已经成功、关闭、退款的订单被再次更新

            if (PaymentKit.verifyNotify(params, mch_key)) {
                if (("SUCCESS").equals(result_code)) {
                    //更新订单信息
                    logger.error("更新商家充值订单信息");
                    RechargeLog log = rechargeLogService.findByOrderNo(orderNo);
                    if(log.getStatus() == 0){
                        //更新日志信息
                        log.setStatus(1);
                        log.setUpdateTime(new Date());
                        rechargeLogService.updateLog(log);

                        //增加商户余额
                        User user = userService.selectUserByUid(log.getuId());
                        BigDecimal fee =new BigDecimal(totalFee).divide(new BigDecimal(100));
                        user.setMoney(user.getMoney().add(fee));
                        userService.updateUser(user);
                    }

                    return "success";
                }
            }
        }
        return new PageData().success(null);
    }

    /**
     * 充值管理界面
     * @param model
     * @return
     */
    @RequestMapping(value = "/recharge_manage.do")
    public String goOrders(HttpSession session, Model model){
        int sessionUid = (int) session.getAttribute("uid");
        User user = userService.selectUserByUid(sessionUid);
        model.addAttribute("user",user);
        return "goRecharge";
    }

    /**
     * 生成充值二维码和交易单
     * @param model
     * @return
     */
    @RequestMapping(value = "/goRecharge.do",method = {RequestMethod.POST})
    public String goRecharge(HttpSession session, Model model){
        int sessionUid = (int) session.getAttribute("uid");
        User user = userService.selectUserByUid(sessionUid);
        BigDecimal money = new BigDecimal(getPageData().getString("money"));
        model.addAttribute("user",user);
        model.addAttribute("money", getPageData().getString("money"));

       //先生成一个充值交易单
        RechargeLog log = new RechargeLog();
        log.setuId(user.getUid());
        log.setStatus(0);
        log.setMoney(money);
        log.setOrderNo(IdWorker.nextId("R"));
        log.setCreateTime(new Date());
        rechargeLogService.save(log);

        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("mch_id", mch_id);
        params.put("body", "充值");
        params.put("out_trade_no",log.getOrderNo());
        params.put("total_fee",money.multiply(new BigDecimal(100)).intValue()+"");

        String ip = IpKit.getRealIp(getRequest());
        if (Tools.isEmpty(ip)) {
            ip = "127.0.0.1";
        }
        params.put("spbill_create_ip", ip);
        params.put("trade_type", "NATIVE");
        params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
        params.put("notify_url", recharge_notify_url);

        String sign = PaymentKit.createSign(params, mch_key);
        params.put("sign", sign);
        String xmlResult = PaymentApi.pushOrder(params);

        Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
        model.addAttribute("code_url",String.valueOf(result.get("code_url")));

        logger.error(xmlResult);
        return "recharge";
    }

    /**
     * 个人充值记录
     * @param model
     * @return
     */
    @RequestMapping(value = "/recharge_record.do")
    public String recharge_record(HttpSession session, Model model){
        int sessionUid = (int) session.getAttribute("uid");
        model.addAttribute("records",rechargeLogService.listAllByUId(sessionUid));
        return "recharge_record";
    }
}
